package com.ethanzzh.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class StuServlet extends HttpServlet {
    String path = null;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String md = req.getParameter("method");

        if (null != md) {
            if ("delStu".equals(md)) {
                path = delStu(req, resp);
            } else if ("findStu".equals(md)) {
                path = findStu(req, resp);
            }
        }
        sendAdd(path,req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收method参数
        String md = req.getParameter("method");
        //通过method不同的取值，执行服务端不同的功能
        if (null != md) {
            if ("addStu".equals(md)) {
                path = addStu(req, resp);
            } else if ("updateStu".equals(md)) {
                path = updateStu(req, resp);
            }
        }
        sendAdd(path,req,resp);
    }

    protected String addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端添加功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";

    }

    protected String delStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端删除功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";
    }

    protected String updateStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端更新功能");
        //由于修改学生这个请求是通过Ajax实现的,是不需要进行转发的，直接响应数据即可
        resp.getWriter().print("updateStuOK");
        return null;
    }

    protected String findStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("执行服务端查找功能");
        //转发到success.jsp
//        req.getRequestDispatcher("/success.jsp").forward(req, resp);
        return "/success.jsp";
    }

    protected void sendAdd(String path,HttpServletRequest req, HttpServletResponse resp) {
        if (path != null) {
            try {
                req.getRequestDispatcher(path).forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}